package com.clouddot.baipai.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.infrastructure.environment.initial.InitialAppType;
import com.clouddot.baipai.model.beam.getClassType.getClassTypeResponse;
import com.clouddot.baipai.ui.dialog.A_netDailog;
import com.clouddot.baipai.ui.service.MyService;
import com.clouddot.baipai.ui.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.ui.util.ToastUtil;
import com.clouddot.baipai.ui.util.getTimeAndWeatherUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import static com.clouddot.baipai.ui.util.netConnectUtil.isNetworkConnected;


/**
 * Created by wxy on 2018/5/2.
 */

public class A_LaunchActivity extends BaseActivity {
    private TextView textView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Environment.getInstance().activities.add(this);

        /**
         * 判断当前的service是否已经启动
         */
        if (!getTimeAndWeatherUtil.isServiceRunning(this,"com.clouddot.baipai.ui.service.MyService")){
            Intent sIntent = new Intent(this, MyService.class);
            startService(sIntent);
        }

    }

    @Override
    protected void setContentView() {
        super.setContentView();
        setContentView(R.layout.a_launch);
    }

    @Override
    protected void onResume() {
        super.onResume();
        View view = getWindow().getDecorView();
        view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    protected Object runThreadActionExceute() {
        return Env.getAppPresenter().getClassType();
    }

    @Override
    protected void runThreadActionSuccess(Object result) {
        super.runThreadActionSuccess(result);
        getClassTypeResponse response = (getClassTypeResponse) result;
        if (response.isSuccess()) {
            Env.getAppContext().type = response.Value;
            Env.getAppContext().DevicePath = response.DevicePath;
            Env.getAppContext().CardReadType = response.CardReadType;
            goToBanPaiype();
        }else{
            Intent intent =  new Intent(A_LaunchActivity.this,H_SettingActivity.class);
            startActivityForResult(intent,1);
        }
    }

    @Override
    protected void runThreadActionError(Exception ex) {
        super.runThreadActionError(ex);
    }

    @Override
    protected void initControls() {
        super.initControls();
        textView = find(R.id.text);
        textView.setText(Env.getAppContext().appName);
        ToastUtil.showToast(this,"网络检查中");
        ThreadPoolFactory.getThread().execute(new Runnable() {
            @Override
            public void run() {
                checkNet();

            }
        });
    }

    @Override
    protected void setListener() {
        super.setListener();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1){
            ThreadPoolFactory.getThread().execute(new Runnable() {
                @Override
                public void run() {
                    checkNet();

                }
            });
        }
    }

    private void goTosetting(){
        final A_netDailog dailog = new A_netDailog(A_LaunchActivity.this);
        textView = dailog.getTextView();

        if(!Env.getAppContext().isInitial){
            textView.setText("当前IP地址为空，请到设置界面设置");
        }else{
            textView.setText("当前的网络不可用，请到设置界面连接网络");
        }
        LinearLayout[] linearLayout = dailog.getBtnView();
        linearLayout[0].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dailog.closeDialog();
                Intent intent =  new Intent(A_LaunchActivity.this,H_SettingActivity.class);
                startActivityForResult(intent,1);
            }
        });
        linearLayout[1].setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dailog.closeDialog();
                checkNet();
            }
        });
        dailog.showDialog();
    }

    /**
     *
     * 检查网络状态
     */
    private int i = 0;
    private void checkNet(){

        while(true) {
            if (isNetworkConnected(this)  && Env.getAppContext().isInitial) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        runThreadAction();
                    }
                });
                break;
        }
        if (i == 3){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    goTosetting();
                }
            });
            break;
        }
        try {
            Thread.sleep(1000);
            i++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        }
    }

    /**
     *
     * 判断进入班牌的类型
     */

    public void goToBanPaiype() {
        Handler handler= new Handler();
        if(Environment.getInstance().Height <= 100){
            handler.postDelayed(new WidthTo1920(), 1500);
        }else{
            handler.postDelayed(new WidthTo751(), 1500);
        }
    }

    /**
     *
     * 进入横屏的班牌
     */
    private class WidthTo1920 implements Runnable{
        public void run() {

            if (Env.getAppContext().type.equals("Common") || Env.getAppContext().type.isEmpty()) {
                if(Env.getAppContext().CardReadType.equals("Serial")) {
                    startActivity(new Intent(getApplication(), H_SMainActivity.class));
                }else if(Env.getAppContext().CardReadType.equals("Usb")){
                    startActivity(new Intent(getApplication(), H_UMainActivity.class));
                }else{
                    ToastUtil.showToast(A_LaunchActivity.this,"读卡类型为空，请到后台去配置班牌的读卡类型");
                }
            } else if (Env.getAppContext().type.equals("Urgent")) {
                startActivity(new Intent(getApplication(), A_UrgentActivity.class));
            } else if (Env.getAppContext().type.equals("Shutdown")) {
                if(Env.getAppContext().CardReadType.equals("Serial")) {
                    Intent intent = new Intent("android.intent.action.shutdown");
                    sendBroadcast(intent);
                }else {
                    try {
                        Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});  //关机
                        proc.waitFor();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if(Env.getAppContext().type.equals("Reboot")){
                if(Env.getAppContext().CardReadType.equals("Serial")) {
                    Intent intent = new Intent("android.intent.action.reboot");
                    sendBroadcast(intent);
                }else {
                    try {
                        Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot "}); //重启
                        proc.waitFor();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
            for( Activity activity : Environment.getInstance().activities){
                activity.finish();
            }
            Environment.getInstance().activities.clear();
        }
    }

    /**
     *
     * 进入竖屏的班牌
     */
    private class WidthTo751 implements Runnable{
        public void run() {
            if (Env.getAppContext().type.equals("Common") || Env.getAppContext().type.isEmpty()) {
                startActivity(new Intent(getApplication(), V_MainActivity.class));
            } else if (Env.getAppContext().type.equals("Urgent")) {
                startActivity(new Intent(getApplication(), A_UrgentActivity.class));
            } else if (Env.getAppContext().type.equals("Shutdown")) {
                try {
                    Process proc = Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot -p"});  //关机
                    proc.waitFor();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if(Env.getAppContext().type.equals("Reboot")){
                try {
                    Process proc =Runtime.getRuntime().exec(new String[]{"su","-c","reboot "}); //重启
                    proc.waitFor();
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
            for( Activity activity : Environment.getInstance().activities){
                activity.finish();
            }
            Environment.getInstance().activities.clear();
        }
    }

}
